import { getToken, setItem } from '@/utils/storage'
import { baseUrl } from './resource'

//请求
function http (opts, token) {
  let httpDefaultOpts = {
    url: opts.custom ? opts.url : baseUrl + opts.url,
    data: opts.params,
    method: opts.method,
    timeout: 20000,
    sslVerify: false,
    dataType: 'json'
  }
  //是否带token
  if (token) {
    httpDefaultOpts.header = { token }
    httpDefaultOpts.data.token = token
  }

  //promise
  let promise = new Promise(function (resolve, reject) {
    let network //网络状态
    //网络状态
    uni.getNetworkType({
      success: function (res) {
        network = res.networkType
        if (res.networkType == 'none') {
          uni.showToast({
            title: '无网络',
            icon: 'none',
            duration: 5000
          })
        }
      }
    })

    uni
      .request(httpDefaultOpts)
      .then(res => {
        //成功
        if (res) {
          if (res.statusCode == 200) {
            const { code, msg } = res.data

            // token失效用户 - 后台删除用户maybe - 判定为新用户
            if (code == -1 && msg) {
              setItem('privacy', true)
              uni.removeStorageSync('token')
              uni.reLaunch({ url: '/pages/launch/index' })
              return
            }

            // token过期用户 - 为已登录的用户 - 需要获取正常数据
            if (code == 404) {
              uni.removeStorageSync('token')
              uni.reLaunch({ url: '/pages/launch/index' })
              return
            }

            // 注销用户 - 进入注销页面
            if (code == 12) {
              uni.reLaunch({ url: '/pages/signout/index' })
              return
            }

            if (code == 0 && msg) {
              reject(msg)
              return
            }

            //请求成功，返回最终需要的业务数据
            resolve(res.data)
          } else {
            let errMsg = ''
            if (res.statusCode == 500) errMsg = '服务器错误'

            //其他情况的失败,返回失败原因
            uni.showToast({
              title: errMsg || res.data?.msg,
              icon: 'none'
            })
            reject(errMsg || res.data?.msg)
          }
        } else {
          //失败
          uni.showToast({
            title: '请求失败',
            icon: 'none'
          })
          reject('请求失败')
        }
      })
      .catch(response => {
        console.log('response', response)

        reject(response)
      })
  })
  return promise
}

//请求
const httpTokenRequest = opts => {
  if (opts.notToken) {
    return http(opts)
  }
  const token = getToken()
  // const token = '78dd11e8173a4810e3264a3f89d356d3'
  // const token = '8c27234764ef7b4a1f72bd16d37fa859'
  opts.params = opts.params || {}
  return http(opts, token)
}

export default httpTokenRequest
